<template>
  <div class="register">
    <h2>注册</h2>
    <el-form :model="registerForm" ref="registerForm" label-width="100px">
      <el-form-item label="姓名">
        <el-input v-model="registerForm.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="选择机构">
        <el-select v-model="registerForm.organization" placeholder="请选择机构">
          <el-option
              v-for="org in organizations"
              :key="org.id"
              :label="org.name"
              :value="org">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="register">注册</el-button>
        <el-button @click="toLogin">返回登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "@/utiles/axios";

export default {
  data() {
    return {
      registerForm: {
        name: "",
        phone: "",
        email: "",
        password: "",
        organizationId: null, // 选择的机构ID
      },
      organizations: [], // 存储机构列表
    };
  },
  mounted() {
    this.fetchOrganizations(); // 组件加载时获取所有机构
  },
  methods: {
    // 获取所有机构列表
    fetchOrganizations() {
      axios
          .get("/organization") // 后端接口获取所有机构
          .then((response) => {
            this.organizations = response.data;
          })
          .catch((error) => {
            console.error("获取机构列表失败:", error);
          });
    },
    // 注册
    register() {
      axios
          .post("/student/register", this.registerForm) // 将注册表单数据提交给后端
          .then(() => {
            this.$message.success("注册成功！");
            this.$router.push("/studentLogin"); // 注册成功后跳转到登录页面
          })
          .catch((error) => {
            this.$message.error(error.response.data || "注册失败！"); // 处理错误信息
          });
    },
    // 跳转到登录页面
    toLogin() {
      this.$router.push("/");
    },
  },
};
</script>

<style>
.register {
  width: 400px;
  margin: 100px auto;
}
</style>
